#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#include <iostream>
#include <cstdlib>
#include <math.h>

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glut.h>
#endif

using namespace std;

#include "Camera.h"

#include "Common.h"

const double PI = 3.14159265;

Camera::Camera(CueBall* _cueBall)
{
   cueBall = _cueBall;
   topView = false;
}

void Camera::position(bool ortho, bool movingBalls) 
{
   if (!movingBalls)
   {   
      o = cueBall->getInitialPosition();
   }

   if (ortho)
   {
      gluLookAt(0, Config::getMaxSceneHeight(), 1, 0, 0, 0, 1, 0, 0);
   }
   else
   {
      gluLookAt(o[0], o[1] + 1818 /*1818*/, o[2] + 6000, o[0], o[1], o[2], 0, 1, 0);
   }
}

void Camera::reshape(int _w, int _h, bool ortho) 
{
   w = _w;
   h = _h;
   
   glViewport(0, 0, (GLsizei)w, (GLsizei)h);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   
   setPerspective(ortho);
   
   glMatrixMode(GL_MODELVIEW); 
}

void Camera::setPerspective(bool ortho)
{
   if (ortho)
   {
      double x = (Config::getTableDepth() / 2) * 1.1;
      double y = (Config::getTableWidth() / 2) * 1.1;
      
      double aspect = (double) h / (double) w;
      
      if ((y/x) < aspect) {
         glOrtho(-x, x, -x * aspect, x * aspect, -1, Config::getMaxSceneHeight() + Config::getTableLift() + 1);            
      }
      else
      {
         glOrtho(-y / aspect, y / aspect, - y, y, -1, Config::getMaxSceneHeight() + 1);      
      }
   }
   else
   {
      //std::cout << 20 <<":"<< (GLfloat)w / (GLfloat)h <<":"<< 4 <<":"<< 1+4*Config::getTableWidth() << std::endl; 
      gluPerspective(20, (GLfloat)w / (GLfloat)h, 4, 1+2*Config::getRoomDepth()); 
   } 
}


